package com.china.produce.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/7/3
 */
@Slf4j
@RequestMapping("/threadPool")
@RestController
public class ThreadPoolController {

    @GetMapping("/threadHasRes")
    public String threadHasRes() throws InterruptedException, ExecutionException {
        ArrayList<Future<String>> futures = new ArrayList<>();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10, true));

        for (int i = 0; i < 30; i++) {
            Future<String> future = executor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(1000);
                    System.out.println("thread name: " + Thread.currentThread().getName());
                    return "haha";
                }
            });
            futures.add(future);
        }

        if (executor.awaitTermination(3, TimeUnit.HOURS)) {
            for (Future<String> future : futures) {
                log.info("res: {}", future.get());
            }
        }

        executor.shutdown();

        return "success";
    }

    @GetMapping("/threadNoRes")
    public String threadNoRes() {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 3, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));

        for (int i = 0; i < 20; i++) {
            executor.execute(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    Thread.sleep(2000);
                    System.out.println("执行成功 ！" + Thread.currentThread().getName());
                }
            });
        }

        executor.shutdown();

        return "success";
    }
}
